const { User } = require('../../model/user');
const bcrypt = require('bcrypt');

module.exports = async (req, res, next) => {
    // get传递过来的数据id
    let id = req.query.id;
    // post传递过来的数据
    let body = req.body;

    let user = await User.findOne({_id: id});

    // 比较用户修改中输入的密码和数据库中存储的加密密码是否一致，一致才会更新数据
    const is_valid = await bcrypt.compare(body.password, user.password);
    if(is_valid){
        // res.send("密码比对成功");
        await User.updateOne({_id: id}, {
            username: body.username,
            email: body.email,
            role: body.role,
            state: body.state
        });

        res.redirect('/admin/user');
    }else{
        let obj = {
            path: '/admin/user-edit',
            message: "密码比对失败, 不能进行用户数据的更新",
            id: id
        };
        next(JSON.stringify(obj));
    }
}